<?php
/**
 * 《通讯簿》管理类
 *
 * @author 孙晓晔
 * @version $Id: Address.class.php 814 2009-12-31 12:32:46Z sunxy $
 */
require_once(dirname(__FILE__) . '/Emp.class.php');

class Address extends Emp {
	
	public $sex = array(
		'-' => '请选择',
		'1' => '男',
		'2' => '女',
	);
	
	public $cb = array(
		// '1' => '头像',
		'2' => '手机',
		'3' => '短号',
		'4' => '分机',
		'5' => '邮箱',	
	);
	
	public $office = array(
		'-' => '请选择',
		'1' => '南山',
		'2' => '沙井',
		'3' => '清溪',
	);

	public $book = array(
		'-' => '请选择',
		'1' => '是',
		'2' => '否',		
	);

	public $status = array(
		'-' => '请选择',
		'1' => '在职',
		'3' => '离职',
	);

	public $orderby = array(
		'-' => '请选择',
		'code' => '编号',
		'name' => '姓名',
		'sex' => '性别',
		'dept' => '部门',
		'job' => '职位',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);

		$this->dsn = '_fy';
		$this->dsn_r = 'fy';
		$this->dsn_w = '_fy';
	}

	function pretreat($controller) {
		$controller->assign_by_ref('office_option', $this->office);
		$controller->assign_by_ref('book_option', $this->book);

		$controller->assign_by_ref('cb_option', $this->cb);
		
		$controller->assign_by_ref('status_option', $this->status);
		$controller->assign_by_ref('orderby_option', $this->orderby);
	}

	/**
	 *
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function layout($controller, $request) {
		$controller->display($request, 'emp/address/index');
		return true;
	}
	
	function x($controller, $request) {
		$controller->display($request, 'emp/address/x');
		return true;
	}

	/**
	 *
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function a($controller, $request) {
		$controller->display($request, 'emp/address/a');
		return true;
	}

	/**
	 *
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function b($controller, $request) {
		$controller->left_delimiter = "#{";
		$controller->right_delimiter = "}#";

		$controller->display($request, 'emp/address/b');
		return true;
	}

	/**
	 * 景荣通讯簿
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function book($controller, $request) {
		$this->pretreat($controller);

		$office = $request['office'];

		$data = array();
		$db = newdb(Constant::tbl_dept);
		$fmt = "SELECT * FROM %s ORDER BY orderby";
		$sql = sprintf($fmt, Constant::tbl_dept);
		// echo $sql;
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$data = array_merge($data, $this->emp_dept($row, $office));
		}

		$controller->assign_by_ref('result', $data);

		if ($this->_emp($controller)) {
			$controller->display($request, 'emp/address/book_my');
		} else {
			$controller->display($request, 'emp/address/book');
		}

		return true;
	}

	function _emp($controller) {
		if (is_array($_SESSION['emp'])) {
			$controller->assign_by_ref('emp', $_SESSION['emp']);
			return true;
		}

		$ip = '192.168.2.30';
		$ip = $_SERVER['REMOTE_ADDR'];
		$emp = $this->_emp_ip($ip);

		if (!$emp) {
			return false;
		}

		if (empty($emp['exten'])) {
			return false;
		}

		$controller->assign_by_ref('emp', $emp);
		return true;
	}

	function _emp_ip($ip) {
		$key = "emp.ip_" . $ip;
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}

		$db = newdb(Constant::tbl_emp);
		$fmt = "SELECT a.* FROM %s a, %s b WHERE a.id = b.emp AND b.ip = '%s'";
		$sql = sprintf($fmt, Constant::tbl_emp, Constant::tbl_emp_mac, $ip);
		// debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) == 0) {
			return false;
		}

		$ret = $db->fetch_array($result);

		if (is_object($mc)) {
			$mc->set($key, $ret, 0, _strtotime("1 day"));
		}

		return $ret;
	}

	function emp_dept($data, $office, $book = '1') {
		$dept = $data['code'];
		$name = $data['name'];

		$ret = array();

		$db = newdb(Constant::tbl_emp);
		$fmt = "SELECT * FROM %s WHERE dept = '%s' AND book = '%s' AND status = '1' ";
		$sql = sprintf($fmt, Constant::tbl_emp, $dept, $book);

		if (!empty($office)) {
			$sql .= " AND office = '" . $office . "'";
		}

		$orderby = " ORDER BY orderby, id";
		$sql .= $orderby;
		// echo $sql;
		$result = $db->query($sql);
		while($row = $db->fetch_array($result)) {
			$row['dept_t'] = $name;
			$ret[] = $row;
		}

		return $ret;
	}

	function t($controller, $request) {
		return $this->dept($controller, $request);
	}

	/**
	 * 景荣通讯簿
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function t_($controller, $request) {
		$this->pretreat($controller);

		$office = $request['office'];

		$data = array();
		$db = newdb(Constant::tbl_dept);
		$fmt = "SELECT * FROM %s WHERE status = '1' AND code LIKE '__' ORDER BY orderby";
		$sql = sprintf($fmt, Constant::tbl_dept);
		// echo $sql;
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {

			$data[] = $row;
		}

		$controller->assign_by_ref('result', $data);

		$controller->display($request, 'emp/address/t');
		return true;
	}

	function tab($controller, $request) {
		$this->pretreat($controller);

		$data = array();
		$db = newdb(Constant::tbl_dept);
		$fmt = "SELECT * FROM %s WHERE status = '1' AND code LIKE '__' ORDER BY orderby";
		$sql = sprintf($fmt, Constant::tbl_dept);
		// echo $sql;
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {

			$data[] = $row;
		}

		$controller->assign_by_ref('result', $data);

		$controller->display($request, 'emp/address/tab');
		return true;
	}
	
	function qx($controller, $request) {
		$this->pretreat($controller);
	
		$data = array();
		$db = newdb(Constant::tbl_dept);
		$fmt = "SELECT DISTINCT(a.code), a.name FROM %s a, %s b WHERE a.code = b.dept AND b.office = '3' AND a.status = '1' AND a.code LIKE '__%s' ORDER BY a.orderby";
		$sql = sprintf($fmt, Constant::tbl_dept, Constant::tbl_emp, '%');
		// echo $sql;
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$row['code'] = substr($row['code'], 0, 2);
			$row['name'] = $this->dept_name($row['code']);
	
			$data[$row['code']] = $row;
		}
		
		debug(print_r($data, true));
	
		$controller->assign_by_ref('result', $data);
	
		$controller->display($request, 'emp/address/qx');
		return true;
	}
	
	function dept_name($code) {
		$db = newdb(Constant::tbl_dept);
		$fmt = "SELECT * FROM %s WHERE code = '%s'";
		$sql = sprintf($fmt, Constant::tbl_dept, $code);
		// debug($sql);
		$result = $db->query($sql);
		
		if ($row = $db->fetch_array($result)) {
			return $row['name'];
		}
		
		return $code;
	}

	function e($controller, $request) {
		$dept = $request['dept'];
		$status = '1';

		$ret = array();

		$db = newdb(Constant::tbl_emp);
		$fmt = "SELECT * FROM %s WHERE dept LIKE '%s__' AND status = '%s' AND book = '1'";
		$sql = sprintf($fmt, Constant::tbl_emp, $dept, $status);

		if (!empty($office)) {
			$sql .= " AND office = '" . $office . "'";
		}
		$orderby = "ORDER BY office, orderby, id";
		$sql .= $orderby;
		debug($sql);
		$result = $db->query($sql);
		while($row = $db->fetch_array($result)) {
			$data[] = $row;
		}

		$controller->assign_by_ref('result', $data);

		if ($this->_emp($controller)) {
			$controller->display($request, 'emp/address/e_my');
		} else {
			$controller->display($request, 'emp/address/e');
		}

		return true;
	}

	function dept($controller, $request) {
		$this->pretreat($controller);

		$dept = $request['dept'];
		
		$data = array();
		$db = newdb(Constant::tbl_dept);
		$fmt = "SELECT * FROM %s WHERE status = '1' AND code LIKE '%s__' ORDER BY orderby";
		$sql = sprintf($fmt, Constant::tbl_dept, $dept);
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {

			$data[] = $row;
		}
		
		if (count($data) == 0) {
			return $this->view($controller, $request);
		}

		$controller->assign_by_ref('result', $data);

		$controller->display($request, 'emp/address/dept');
		return true;
	}

	var $_tab = 0;
	function tree($title, $data) {
		$class = "Closed";
		if (array_key_exists("class", $data)) {
			$class = $data['class'];
		}
			
		$ret = "<li class=\"$class\"><img class=s src=\"/images/s.gif\" onclick=\"menutree(this);\"><a href=\"javascript:void(0)\" onclick=\"menutree(this);\">$title</a>
    <ul>\n";

		$submenu = '';
		foreach ($data as $k => $v) {
			if ($k == 'class') {
				continue;
			}
				
			if ($k == "返回") {
				$submenu .= "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"$v\">$k</a></li>\n";
			} else {
				$submenu = $this->_tree($submenu, $k, $v);
			}

			/*
			 	

			if (is_array($v) && !array_key_exists('cc', $v)) {
			$submenu .= $this->tree($k, $v);
			} else {
			if ($k == "返回") {
			$submenu .= "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"$v\">$k</a></li>\n";
			} else {
			$submenu .= "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"javascript:void(0)\" onClick=\"menu('" . $v['cc'] . "', '#placeholder', '" . $v['js'] . "')\">$k</a></li>\n";
			}
			}*/
		}

		if (empty($submenu)) {
			return '';
		}

		$ret .= $submenu . "</ul>
  </li>\n";

		return $ret;
	}

	function _tree($submenu, $k, $v) {
		if ($k == "退出") {
			return $submenu . "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"$v\">$k</a></li>\n";
		}

		if (!is_array($v)) {
			return $submenu;
		}

		if (array_key_exists('dd', $v)) {
			return $submenu . "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"javascript:void(0)\" onClick=\"menu('" . $v['dd'] . "', '#placeholder')\">$k</a></li>\n";
		}
			
		if (array_key_exists('cc', $v)) {
			return $submenu . "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"javascript:void(0)\" onClick=\"menu('" . $v['cc'] . "', '#placeholder')\">$k</a></li>\n";
		}

		if (array_key_exists('tt', $v)) {
			$this->_tab += 3;
			$fmt = "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"javascript:void(0)\" onClick=\"tab('%s', '%s', '%s', '%s')\">%s</a></li>\n";
			return $submenu . sprintf($fmt, $v['tt'], '#placetab', $this->_tab, $k, $k);
		}

		if (array_key_exists('bb', $v)) {
			$this->_tab += 3;
			$fmt = "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"javascript:void(0)\" onClick=\"tab22('%s', '%s', '%s', '%s')\">%s</a></li>\n";
			return $submenu . sprintf($fmt, $v['bb'], '#placetab', $this->_tab, $k, $k);
		}
			
		return $submenu . $this->tree($k, $v);
	}

	function find($controller, $request) {
		$this->pretreat($controller);

		$controller->display($request, 'emp/address/find');
		return true;
	}

	function findPost($controller, $request) {
		$this->pretreat($controller);

		$name_s = $request['name_s'];

		$office_s = $request['office_s'];
		$dept_s = $this->_input($request['dept_s']);

		$mobile_s = $request['mobile_s'];
		$exten_s = $request['exten_s'];

		$book_s = $request['book_s'];
		
		$cb_s = $request['cb_s'];
		// print_r($cb_s);

		$status_s = $request['status_s'];

		$db = newdb($this->dsn);
		$fmt = "SELECT * FROM %s ";
		$sql = sprintf($fmt, Constant::tbl_emp);
		$where = " WHERE status = 1 ";

		if (!empty($name_s)) {
			$where .= " AND name like '" . $name_s . "%'";
		}

		if (!empty($office_s) && $office_s <> '-') {
			$where .= " AND office = '" . $office_s . "'";
		}

		if (!empty($dept_s) && $dept_s <> '-') {
			$where .= " AND dept LIKE '" . $dept_s . "%'";
		}

		if (!empty($mobile_s)) {
			$where .= " AND mobile like '%" . $mobile_s . "%'";
		}

		if (!empty($exten_s)) {
			$where .= " AND exten = '" . $exten_s . "'";
		}

		if (!empty($book_s) && $book_s <> '-') {
			$where .= " AND book = '" . $book_s . "'";
		}
		
		if (count($cb_s) > 0 && in_array(2, $cb_s)) {
			$where .= " AND LENGTH(mobile) > 0";
		}
		
		if (count($cb_s) > 0 && in_array(3, $cb_s)) {
			$where .= " AND LENGTH(short) > 0";
		}
		
		if (count($cb_s) > 0 && in_array(4, $cb_s)) {
			$where .= " AND LENGTH(exten) > 0";
		}
		
		if (count($cb_s) > 0 && in_array(5, $cb_s)) {
			$where .= " AND LENGTH(email) > 0";
		}

		$orderby_s = $request['orderby_s'];
		if (empty($orderby_s) || $orderby_s == '-') {
			$orderby_s = "office, dept, orderby";
		}
		$orderby = " ORDER BY " . $orderby_s;

		$sql .= $where . $orderby;
		debug($sql);

		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			
			$row['sex_t'] = $this->sex[$row['sex']];
			$row['office_t'] = $this->office[$row['office']];
			$row['dept_t'] = $this->dept_option[$row['dept']];
				
			$row['vacation'] = $this->_has_vacation($row['id']);
				
			$row['mobile_t'] = $this->_mobile_t($row['mobile']);

			// $row = $this->_orderby_x($controller, $row, $orderby_s);

			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);

		if ($this->_emp($controller)) {
			$controller->display($request, 'emp/address/list_my');
		} else {
			$controller->display($request, 'emp/address/list');
		}
		return true;
	}

	function tec($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn);
		$fmt = "SELECT * FROM %s WHERE status = 1 AND book = '1' ORDER BY office, dept";
		$sql = sprintf($fmt, Constant::tbl_emp);
		debug($sql);

		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {

			$row['sex'] = $this->sex[$row['sex']];

			$row['office'] = $this->office[$row['office']];
			$row['dept_t'] = $this->dept_option[$row['dept']];

			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);

		$controller->display($request, 'emp/address/tec');
		return true;
	}
	
	function _mobile_t($s) {
		require_once(dirname(__FILE__) . '/../tel/Mobile.class.php');
		$aa = new Mobile();
	
		if ($row = $aa->_mobile($s)) {
			return $row['city'];
		}
	
		return '';
	}

	function view($controller, $request) {
		$dept = $request['dept'];
		$book = $request['book'];
		
		$status = '1';

		$data = array();
		$db = newdb(Constant::tbl_emp);
		if (empty($book) || $book == '-') {
			$fmt = "SELECT * FROM %s WHERE dept LIKE '%s' AND state IN ('4', '5', '6', '7') AND status = '%s'";
		} else {
			$fmt = "SELECT * FROM %s WHERE dept LIKE '%s' AND state IN ('4', '5', '6', '7') AND status = '%s' AND book = '1'";
		}
		$sql = sprintf($fmt, Constant::tbl_emp, $dept . "%", $status);
		$orderby = " ORDER BY office, orderby, id";
		$sql .= $orderby;
		debug($sql);
		$result = $db->query($sql);
		while($row = $db->fetch_array($result)) {
			$row['sex_t'] = $this->sex[$row['sex']];
			$row['office_t'] = $this->office[$row['office']];
			
			$row['vacation'] = $this->_has_vacation($row['id']);
			
			$row['mobile_t'] = $this->_mobile_t($row['mobile']);
			
			$data[] = $row;
		}

		$controller->assign_by_ref('result', $data);

		if ($this->_emp($controller)) {
			$controller->display($request, 'emp/address/view_my');
		} else {
			$controller->display($request, 'emp/address/view');
		}

		return true;
	}
	
	function _has_vacation($emp) {
		require_once(dirname(__FILE__) . '/../kq/Vacation.class.php');
		$vacation = new Vacation();
		
		return $vacation->_has_vacation($emp);
	}
	
	function view_qx($controller, $request) {
		$dept = $request['dept'];
		$book = $request['book'];
	
		$status = '1';
	
		$data = array();
		$db = newdb(Constant::tbl_emp);
		$fmt = "SELECT * FROM %s WHERE office = '3' AND dept LIKE '%s' AND state IN ('4', '5', '6', '7') AND status = '%s'";
		
		$sql = sprintf($fmt, Constant::tbl_emp, $dept . "%", $status);
		$orderby = " ORDER BY office, dept, orderby, id";
		$sql .= $orderby;
		debug($sql);
		$result = $db->query($sql);
		while($row = $db->fetch_array($result)) {
			$row['sex_t'] = $this->sex[$row['sex']];
			$row['office_t'] = $this->office[$row['office']];
			
			$row['vacation'] = $this->_has_vacation($row['id']);
			$row['mobile_t'] = $this->_mobile_t($row['mobile']);
				
			$data[] = $row;
		}
	
		$controller->assign_by_ref('result', $data);
	
		if ($this->_emp($controller)) {
			$controller->display($request, 'emp/address/view_my');
		} else {
			$controller->display($request, 'emp/address/view');
		}
	
		return true;
	}

	function vcf_($controller, $request) {
		$id = $request['id'];
		$dept = $request['dept'];
		$batch = $request['batch'];

		$charset = $request['charset'];
		if (empty($charset)) {
			$charset = "GBK";
		}

		$db = newdb($this->dsn_r);
		if (!empty($id)) {
			$fmt = "SELECT id, name, photo, job, `short`, exten, email FROM %s WHERE id = '%s'";
			$sql = sprintf($fmt, Constant::tbl_emp, $id);
			$filename = sprintf("%s.vcf", $id);
		} elseif (!empty($dept)) {
			$fmt = "SELECT id, name, photo, job, `short`, exten, email FROM %s WHERE dept LIKE '%s' AND book = 1 AND status = 1 ORDER BY dept";
			$sql = sprintf($fmt, Constant::tbl_emp, $dept . "%");
			$filename = sprintf("tec_%s_%s.vcf", Name::dept($dept), date("Y-m-d"));
			if ($charset == 'GBK') {
				$filename = $this->_utf2gbk($filename);
			}
		} elseif (!empty($batch)) {
			$insql = $this->_batch_insql($request);
				
			$fmt = "SELECT id, name, photo, job, `short`, exten, email FROM %s WHERE book = 1 AND status = 1 AND id %s ORDER BY dept";
			$sql = sprintf($fmt, Constant::tbl_emp, $insql);
			$filename = sprintf("tec_%s.vcf", date("Y-m-d"));
		} else {
			$fmt = "SELECT id, name, photo, job, `short`, exten, email FROM %s WHERE book = 1 AND status = 1 ORDER BY dept";
			$sql = sprintf($fmt, Constant::tbl_emp);
			if ($charset == 'GBK') {
				$filename = sprintf("tec_%s.vcf", date("Y-m-d"));
			}
		}

		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_fn($row['name'], $row, $charset);
			/*	
			$row['first'] = base64_encode($row['first']);
			$row['last'] = base64_encode($row['last']);
			$row['name'] = base64_encode($row['name']);
			$row['job'] = base64_encode($row['job']);
				*/
			
			if ($charset == 'GBK') {
				$row['name'] = $this->_utf2gbk($row['name']);
				$row['job'] = $this->_utf2gbk($row['job']);
			}
				
			$row['photo_t'] = $this->_photo($row);
			$row['photo_base64'] = $this->_photo_base64($row['photo_t']);
			$ret[] = $row;
				
			// debug(print_r($row, true));
		}

		// debug(print_r($ret, true));

		$controller->assign_by_ref('result', $ret);

		header('Content-Disposition:text/vcf; filename=' . $filename);

		if ($charset == 'GBK') {
			header('Content-Type:text/vcf;charset=GBK');
		}

		$controller->display($request, 'emp/address/vcf');
		return true;
	}
	
	function vcf($controller, $request) {
		$id = $request['id'];
		$dept = $request['dept'];
		$batch = $request['batch'];

		$db = newdb($this->dsn_r);
		if (!empty($id)) {
			$fmt = "SELECT id, name, photo, job, `short`, exten, email FROM %s WHERE id = '%s'";
			$sql = sprintf($fmt, Constant::tbl_emp, $id);
			$filename = sprintf("%s.vcf", $id);
		} elseif (!empty($dept)) {
			$fmt = "SELECT id, name, photo, job, `short`, exten, email FROM %s WHERE dept LIKE '%s' AND book = 1 AND status = 1 ORDER BY dept";
			$sql = sprintf($fmt, Constant::tbl_emp, $dept . "%");
			$filename = sprintf("tec_%s_%s.vcf", Name::dept($dept), date("Y-m-d"));
		} elseif (!empty($batch)) {
			$insql = $this->_batch_insql($request);
				
			$fmt = "SELECT id, name, photo, job, `short`, exten, email FROM %s WHERE book = 1 AND status = 1 AND id %s ORDER BY dept";
			$sql = sprintf($fmt, Constant::tbl_emp, $insql);
			$filename = sprintf("tec_%s.vcf", date("Y-m-d"));
		} else {
			$fmt = "SELECT id, name, photo, job, `short`, exten, email FROM %s WHERE book = 1 AND status = 1 ORDER BY dept";
			$sql = sprintf($fmt, Constant::tbl_emp);
			if ($charset == 'GBK') {
				$filename = sprintf("tec_%s.vcf", date("Y-m-d"));
			}
		}

		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_fn($row['name'], $row, $charset);
			
			$row['first'] = quoted_printable_encode($row['first']);
			$row['last'] = quoted_printable_encode($row['last']);
			$row['name'] = quoted_printable_encode($row['name']);
			$row['job'] = quoted_printable_encode($row['job']);
				
			$row['photo_t'] = $this->_photo($row);
			$row['photo_base64'] = $this->_photo_base64($row['photo_t']);
			$ret[] = $row;
		}

		$controller->assign_by_ref('result', $ret);

		header('Content-Disposition:text/vcf; filename=' . $filename);

		$controller->display($request, 'emp/address/vcf');
		return true;
	}

	function foxmail($controller, $request) {
		$request['tpl'] = "txt";
		
		$id = $request['id'];
		$dept = $request['dept'];
		$batch = $request['batch'];

		$db = newdb($this->dsn_r);
		if (!empty($id)) {
			$fmt = "SELECT id, name, photo, job, `short`, exten, email FROM %s WHERE id = '%s'";
			$sql = sprintf($fmt, Constant::tbl_emp, $id);
			$filename = sprintf("%s.csv", $id);
		} elseif (!empty($dept)) {
			$fmt = "SELECT id, name, photo, job, `short`, exten, email FROM %s WHERE dept LIKE '%s' AND book = 1 AND status = 1 ORDER BY dept";
			$sql = sprintf($fmt, Constant::tbl_emp, $dept . "%");
			$filename = sprintf("tec_%s_%s.csv", Name::dept($dept), date("Y-m-d"));
		} elseif (!empty($batch)) {
			$insql = $this->_batch_insql($request);
				
			$fmt = "SELECT id, name, photo, job, `short`, exten, email FROM %s WHERE book = 1 AND status = 1 AND id %s ORDER BY dept";
			$sql = sprintf($fmt, Constant::tbl_emp, $insql);
			$filename = sprintf("tec_%s.csv", date("Y-m-d"));
		} else {
			$fmt = "SELECT id, name, photo, job, `short`, exten, email FROM %s WHERE book = 1 AND status = 1 ORDER BY dept";
			$sql = sprintf($fmt, Constant::tbl_emp);
			if ($charset == 'GBK') {
				$filename = sprintf("tec_%s.csv", date("Y-m-d"));
			}
		}

		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
				
			$ret[] = $row;
		}

		$controller->assign_by_ref('result', $ret);

		$content = $controller->sunxy($request, 'emp/address/foxmail');
		$content = iconv("UTF-8", "GBK", $content);
		
		header('Content-Disposition:text/csv; filename=' . $filename);
		
		$controller->assign_by_ref('content', $content);
		$controller->display($request, 'gbk');
		return true;
	}
	
	function _batch_insql($request) {
		$insql = "in ('000000000";
		while (list($k, $v) = each($request)) {
			if (substr($k, 0, 2) == "c_") {
				$insql .= "', '" . $v;
			}
		}
		$insql .= "')";

		return $insql;
	}

	function _photo($data) {
		$ret = Download::url2('emp', $data['id'], $data['photo']);

		if (!preg_match("/^http/", $ret)) {
			if ($_SERVER["SERVER_PORT"] == '80') {
				$ret = "http://" . $_SERVER["SERVER_NAME"] . $ret;
			} else {
				$ret = "http://" . $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $ret;
			}
		}

		return $ret;
	}

	function _photo_base64($url) {
		// $s = "http://ns.tecmold.com/upload/tt/emp/964/3082524854b984dad3c1b1.JPG";
		debug($url);
		$buf = file_get_contents($url);
		// debug($buf);

		return chunk_split(base64_encode($buf));
		// $base64 = sprintf("PHOTO;ENCODING=BASE64;JPEG:%s", base64_encode($buf));
		// return chunk_split($base64);
		// return chunk_split($base64, 76, "\r\n");
	}

	function quoted_printable_encode($input, $line_max = 75) {
		$hex = array('0','1','2','3','4','5','6','7',
                          '8','9','A','B','C','D','E','F');
		$lines = preg_split("/(?:\r\n|\r|\n)/", $input);
		$linebreak = "=0D=0A=\r\n";
		/* the linebreak also counts as characters in the mime_qp_long_line
		 * rule of spam-assassin */
		$line_max = $line_max - strlen($linebreak);
		$escape = "=";
		$output = "";
		$cur_conv_line = "";
		$length = 0;
		$whitespace_pos = 0;
		$addtl_chars = 0;

		// iterate lines
		for ($j=0; $j<count($lines); $j++) {
			$line = $lines[$j];
			$linlen = strlen($line);

			// iterate chars
			for ($i = 0; $i < $linlen; $i++) {
				$c = substr($line, $i, 1);
				$dec = ord($c);

				$length++;

				if ($dec == 32) {
					// space occurring at end of line, need to encode
					if (($i == ($linlen - 1))) {
						$c = "=20";
						$length += 2;
					}

					$addtl_chars = 0;
					$whitespace_pos = $i;
				} elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) {
					$h2 = floor($dec/16); $h1 = floor($dec%16);
					$c = $escape . $hex["$h2"] . $hex["$h1"];
					$length += 2;
					$addtl_chars += 2;
				}

				// length for wordwrap exceeded, get a newline into the text
				if ($length >= $line_max) {
					$cur_conv_line .= $c;

					// read only up to the whitespace for the current line
					$whitesp_diff = $i - $whitespace_pos + $addtl_chars;

					/* the text after the whitespace will have to be read
					 * again ( + any additional characters that came into
					 * existence as a result of the encoding process after the whitespace)
					 *
					 * Also, do not start at 0, if there was *no* whitespace in
					 * the whole line */
					if (($i + $addtl_chars) > $whitesp_diff) {
						$output .= substr($cur_conv_line, 0, (strlen($cur_conv_line) -
						$whitesp_diff)) . $linebreak;
						$i =  $i - $whitesp_diff + $addtl_chars;
					} else {
						$output .= $cur_conv_line . $linebreak;
					}

					$cur_conv_line = "";
					$length = 0;
					$whitespace_pos = 0;
				} else {
					// length for wordwrap not reached, continue reading
					$cur_conv_line .= $c;
				}
			} // end of for

			$length = 0;
			$whitespace_pos = 0;
			$output .= $cur_conv_line;
			$cur_conv_line = "";

			if ($j<=count($lines)-1) {
				$output .= $linebreak;
			}
		} // end for

		return trim($output);
	} // end quoted_printable_encode

	function _quotedPrintableEncode($input , $line_max = 76) {
		$eol = "\r\n";
		$lines  = preg_split("/\r?\n/", $input);
		$escape = '=';
		$output = '';

		while (list($idx, $line) = each($lines)) {
			$newline = '';
			$i = 0;

			while (isset($line[$i])) {
				$char = $line[$i];
				$dec  = ord($char);
				$i++;

				if (($dec == 32) && (!isset($line[$i]))) {
					// convert space at eol only
					$char = '=20';
				} elseif ($dec == 9 && isset($line[$i])) {
					; // Do nothing if a TAB is not on eol
				} elseif (($dec == 61) || ($dec < 32) || ($dec > 126)) {
					$char = $escape . sprintf('%02X', $dec);
				} elseif (($dec == 46) && (($newline == '')
				|| ((strlen($newline) + strlen("=2E")) >= $line_max))
				) {
					// Bug #9722: convert full-stop at bol,
					// some Windows servers need this, won't break anything (cipri)
					// Bug #11731: full-stop at bol also needs to be encoded
					// if this line would push us over the line_max limit.
					$char = '=2E';
				}

				// Note, when changing this line, also change the ($dec == 46)
				// check line, as it mimics this line due to Bug #11731
				// EOL is not counted
				if ((strlen($newline) + strlen($char)) >= $line_max) {
					// soft line break; " =\r\n" is okay
					$output  .= $newline . $escape . $eol;
					$newline  = '';
				}
				$newline .= $char;
			} // end of for
			$output .= $newline . $eol;
			unset($lines[$idx]);
		}
		// Don't want last crlf
		$output = substr($output, 0, -1 * strlen($eol));
		return $output;
	}

	function _utf2gbk($s) {
		if (empty($s)) {
			return '';
		}

		return iconv("UTF-8", "GBK", $s);
	}

	function _fn($s, $ret, $charset) {
		if (empty($s)) {
			return '';
		}
		
		if ($charset == 'GBK') {	
			$ret['first'] = $this->_utf2gbk(substr($s, 0, 3));
			$ret['last'] = $this->_utf2gbk(substr($s, 3));
		} else {		
			$ret['first'] = substr($s, 0, 3);
			$ret['last'] = substr($s, 3);
		}

		return $ret;
	}

	function g($controller, $request) {
		$s = "1sxy";
		$s = "3sxy";

		if (preg_match("/^(\d+)(.+)/", $s, $m)) {
			print_r($m);
		} else {
			echo "222";
		}

		echo "\n" . $_REQUEST['do'] . "\n";

		logdate($controller, $request);
		return true;
	}
}